package blatt1;

//
//the Ball World game
//Described in Chapter 5 of
//Understanding Object-Oriented Programming with Java
//by Timothy A Budd
//Published by Addison-Wesley
//
//see ftp://ftp.cs.orst.edu/pub/budd/java/ReadMe.html
//for further information
//

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.*;

public class BallWorld extends Frame {

	public static void main(String[] args) {
		BallWorld world = new BallWorld(Color.red);
		world.setVisible(true);

		// Close window
		world.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});

	}

	private static final int FrameWidth = 600;
	private static final int FrameHeight = 400;
	private MovableBall aBall;
	private int counter = 0;

	private BallWorld(Color ballColor) {
		// constructor for new ball world
		// resize our frame
		setSize(FrameWidth, FrameHeight);
		setTitle("Ball World");

		// Set random color
		ballColor = new Color(getRandomValue(), getRandomValue(),
				getRandomValue());

		// initialize object data field
		aBall = new MovableBall(10, 15, 10);
		aBall.setColor(ballColor);
		aBall.setMotion(3.0, 6.0);

	}

	/**
	 * Get Value for RGB between 0-255
	 * 
	 * @return
	 */
	private int getRandomValue() {
		return (int) (Math.random() * 255);
	}

	public void paint(Graphics g) {
		super.paint(g);
		// first, draw the ball

		aBall.paint(g);
		// then move it slightly

		switch (counter) {
		case 0:
			aBall.move();
			counter++;
			break;
		case 15:
			counter = 0;
			break;
		default:
			counter++;
		}
//		aBall.move();

		if ((aBall.x() < 0) || (aBall.x() > FrameWidth)){
			aBall.setMotion(-aBall.xMotion(), aBall.yMotion());
			aBall.move();
		}
		if ((aBall.y() < 0) || (aBall.y() > FrameHeight)){
			aBall.setMotion(aBall.xMotion(), -aBall.yMotion());
			aBall.move();
		}
		// finally, redraw the frame
		// counter = counter + 1;
		// if (counter < 2000)
		// repaint();
		// else
		// System.exit(0);
		repaint();

	}
}
